var express = require('express');
var router = express.Router();
const {Course,Like,User} = require('../models')
const {success,failure, NotFoundError} = require('../utils/response')

//用户点赞课程接口
router.post('/',async function (req,res){
    try {
        const userId = req.userId
        const {courseId} = req.body
        const course = await Course.findByPk(courseId)
        if(!course){
            throw new NotFoundError('课程不存在')
        }

        const like = await Like.findOne({
            where:{
                courseId,
                userId
            }
        })

        // 点赞记录不存在则点赞，点赞记录已存在则取消点赞，即删除like表中的一条数据
        if(!like){
            await Like.create({courseId,userId})
            // 让指定字段的值增加,增加值可自定义,默认1
            await course.increment('likesCount')
            success(res,'点赞成功')
        }else{
            await like.destroy()
            // 让指定字段的值减少,减少值可自定义,默认1
            await course.decrement('likesCount')
            success(res,'取消点赞成功')
        }

    } catch (error) {  
        failure(res,error)
    }
})


router.get('/likeSearch',async (req,res) => {
    try {
        const query = req.query
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (currentPage-1)*pageSize

        const user = await User.findByPk(req.userId)

        // likecourses是在多对多关联中定义的模型，可以使用此方法查询，注意要驼峰命名
        const courses = await user.getLikeCourses({
            // 查询关联表为空，代表不查询关联表
            joinTableAttributes:[],
            attributes:{exclude:['categoryId','userId','content']},
            order:[['id','DESC']],
            limit:pageSize,
            offset:offset,
        })
        
        // sequelize提供的获取数量的方法，注意也要驼峰命名
        const count = await user.countLikeCourses()

        success(res,'查询当前用户点赞的课程成功',{
            courses,
            pagination:{
                total:count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res,error)
    }
})


module.exports = router